import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import json


from matplotlib.pylab import style #自定义图表风格
style.use('ggplot')

# 解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['Simhei']
# 解决坐标轴刻度负号乱码
plt.rcParams['axes.unicode_minus'] = False

#pip install statsmodels
from statsmodels.graphics.tsaplots import plot_acf,plot_pacf  #自相关图、偏自相关图
from statsmodels.tsa.stattools import adfuller as ADF #平稳性检验
from statsmodels.stats.diagnostic import acorr_ljungbox #白噪声检验
import statsmodels.api as sm #D-W检验,一阶自相关检验
from statsmodels.graphics.api import qqplot #画QQ图,检验一组数据是否服从正态分布
from statsmodels.tsa.arima.model import ARIMA

with open('../saleByTopFromSeries.json','r',encoding='utf-8') as f:
    listRS = json.load(f)
for index in range(len(listRS)):
    pyearAndMonth = listRS[index]["yearAndMonth"]
    yearAndMonth = pyearAndMonth[:42]
    psalesData= listRS[index]["salesData"]
    salesData = psalesData[:42]
    series = listRS[index]["series"]
    seriesId = listRS[index]["seriesId"]

    # 创建字典对象
    pdata = {"date":pyearAndMonth,"sale":psalesData}

    # 创建dataframe
    psale = pd.DataFrame(pdata)

    # # 转换日期数据类型
    # index = pd.DatetimeIndex(yearAndMonth)

    # 将日期设置索引值
    psale.set_index(['date'],inplace=True)

    # 转换销售量数据类型
    psale.sale=psale.sale.astype('float')

    # 历史数据长度
    g_datalen = len(salesData)

    # 创建字典对象
    data = {"date":yearAndMonth,"sale":salesData}

    # 创建dataframe
    sale = pd.DataFrame(data)

    # # 转换日期数据类型
    # index = pd.DatetimeIndex(yearAndMonth)

    # 将日期设置索引值
    sale.set_index(['date'],inplace=True)

    # 转换销售量数据类型
    sale.sale=sale.sale.astype('float')

    primitiveSale = sale

    d = 0
    while(True):
        print("---------------------第{}次计算---------------------:\n".format(str(d+1)),
              "单位根检验：",ADF(sale.sale),"\n白噪声检验：",acorr_ljungbox(sale,lags=1))
        if (ADF(sale.sale)[1]<0.05) and (acorr_ljungbox(sale,lags=1)['lb_pvalue'].values[0]<0.05):
            break
        elif d>9:
            break
        else:
            d = d+1
            sale=sale.diff(periods=1, axis=0).dropna()
#     print("\n经历了{}阶差分".format(str(d)))
    (p, q) =(sm.tsa.arma_order_select_ic(sale,max_ar=3,max_ma=3,ic='aic')['aic_min_order'])

    #创建模型
    model=ARIMA(primitiveSale,order=(p,d,q)).fit()
    #预测
    print('未来6月的销量预测：')
    forecast = model.forecast(6) #预测、标准差、置信区间
    plt.plot(pd.DatetimeIndex(psale.index), psale.sale, label="原始数据",color="b")
    plt.plot(pd.DatetimeIndex(primitiveSale.index), primitiveSale.sale, label="阉割数据",color="g")
    plt.plot(forecast.index, forecast.values, label="预测结果",color="r")
    plt.legend(loc="upper left")
    plt.title(series + "汽车销量预测")  # 图形标题
    plt.savefig("./img/" + seriesId + 'af_sale.jpg')
    plt.pause(1)
    plt.close()


